package org.teamh.connection.refresh;

import java.util.LinkedList;

import org.teamh.game.StartGame;
import org.teamh.gui.Event;
import org.teamh.logic.lobby.Game;
import org.teamh.logic.lobby.Player;

public class RefreshLobby extends Thread {

	private StartGame start;
	private boolean running;
	
	public RefreshLobby(StartGame start) {
		this.start = start;
		this.running = true;
	}
	
	@Override
	public void run() {
		synchronized (start) {
			start.getModel().setPlayers(new LinkedList<Player>());
			start.getModel().setGames(new LinkedList<Game>());
			start.getConnection().sendMessage("LIST USERS");
			start.getConnection().sendMessage("LIST GAMES");
			
			start.getGui().addEvent(new Event("player", start.getModel().getPlayers()));
			start.getGui().addEvent(new Event("games", "", start.getModel().getGames()));
		}
		
		while(running) {
			
//			try {
//				sleep(1500);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			
			synchronized (start) {	
				if(start.getConnection().getSocket().isClosed()) {
					return;
				}
				
				start.getModel().setPlayers(new LinkedList<Player>());
				start.getModel().setGames(new LinkedList<Game>());			
				start.getConnection().sendMessage("LIST USERS");
				start.getConnection().sendMessage("LIST GAMES");
				
				try {
					sleep(1500);
					start.getGui().addEvent(new Event("player", start.getModel().getPlayers()));
					start.getGui().addEvent(new Event("games", "", start.getModel().getGames()));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}
	}
	
	/**
	 * To shutdown the thread if lobby is no longer needed
	 */

	public void shutdown() {
		running = false;
	}
}
